<template>   
    <Form ref="formItem" :model="formItem" :label-width="100" :rules="ruleValidate">
        <FormItem label="请假种类" prop="teacher_leave_kind">
            <Select v-model="formItem.teacher_leave_kind" >
                <Option v-for="item in DictionaryList" :value="item.dictionary_id" :key="item.dictionary_id">{{ item.dictionary_name.zh?item.dictionary_name.zh:item.dictionary_name.mn }}</Option>
            </Select>
        </FormItem>
        <FormItem label="请假时间" >
            <DatePicker type="datetimerange" format="yyyy-MM-dd HH:mm" v-model="leavedate" @on-change="selDate" placeholder="请选择请假时间" style="width: 100%"></DatePicker>
        </FormItem>
        <FormItem label="请假天数" prop="leave_days">
            <Input v-model="formItem.leave_days" placeholder="请假天数"></Input>
        </FormItem>
        <FormItem label="是否调课" prop="whether_class">
            <Select v-model="formItem.whether_class" @on-change="whether">
                <Option :value="1" :key="1">是</Option>
                <Option :value="2" :key="2">否</Option>
            </Select>
        </FormItem>
        <FormItem label="调课安排" v-if="formItem.whether_class=='1'">
            <div class="cont-table" >
                <Select v-model="curriculumId" style="width:50%;padding-bottom:10px;" @on-change="formState">
                    <Option v-for="item in curriculumList" :value="item.id" :key="item.id">{{ item.name.zh?item.name.zh:item.name.mn }}</Option>
                </Select>
                <Table :columns="columns1" height="200" :data="courselist" :loading="tableload"></Table>
            </div>
        </FormItem>
        <FormItem label="教师请假原因">
            <Input v-model="formItem.teacher_leave_reason.zh" type="textarea" :autosize="{minRows: 2,maxRows: 4}" placeholder="请假原因"></Input>                                       
        </FormItem>
        <FormItem>
            <Button type="primary" @click="submit('formItem')" :loading="btnload">修改</Button>
        </FormItem>
    </Form>
</template>

<script>
export default {
    props:['infoId'],
    data () {
        return {
            leavedate:[],
            time_status:'',
            curriculumId:null,
            curriculumList:[],
            leavedate:[],
            btnload:false,
            tableload:false,
            courselist:[],
            DictionaryList:[],
            infoOld:null,
            editUrl:'api/leave/v1/teacher_leave/getone/',
            updateUrl:'api/leave/v1/teacher_leave/all_teacher_update/',
            formItem: {     
                start_time:'',
                end_time:'',  
                teacher_leave_id:this.infoId, 
                teacher_leave_kind:null,
                whether_class:'',
                teacher_leave_reason:{
                    zh:'',mn:'',en:'',
                },
                class:[],
                leave_days:'',
            },
            ruleValidate: {
                'leave_days':[
                    { required: true, message: '请输入请假天数', trigger: 'blur' }
                ],
                whether_class: [
                    { required: true, type: 'number', message: '请选择是否调课', trigger: 'change' }
                ],
                teacher_leave_kind: [
                    { required: true, type: 'number', message: '请选择请假种类', trigger: 'change' }
                ],
            },
            columns1:[
                {
                    title: '课程',				
                    align: 'center',
                    key:'course',
                },
                {
                    title: '教师',
                    align: 'center',
                    render: (h, params) => {
                        let ss=[]
                            params.row.teacher.forEach((item)=>{
                            ss.push(h('Option', {
                                props: {
                                    value:item.value,
                                    }
                                },item.label))
                            })
                        return h('Select',{
                            props:{
                                value:params.row.seleced_id ? params.row.seleced_id : '',//默认选中第一个（v-model）
                                clearable:true
                            },
                            on:{
                                'on-change':(value) => {
                                    let arr={
                                        user_id:value,
                                        course_arrange_id:params.row.course_arrange_id,
                                        cycle:params.row.cycle
                                    }
                                    if(this.formItem.class[params.index]&&this.formItem.class[params.index].user_id == arr.user_id){
                                        this.formItem.class[params.index]=arr
                                    }else if(value!=undefined){
                                        this.formItem.class.push(arr)
                                    }
                                },
                                'on-clear':()=>{
                                    let a = this.formItem.class.findIndex(el=>el==this.formItem.class[params.index])
                                    let b = this.formItem.class.find((el,ind)=>ind==a)  
                                    b.user_id = ''
                                },
                            }
                        },ss);
                    },
                },
            ],
        }
    },
    methods: {
        /************************************************************
         * 处理时间
         ************************************************************/
        selDate(val){ 
            this.time_status = ''
            this.formItem.start_time = val[0] 
            this.formItem.end_time = val[1]    
        },
        /************************************************************
         * 获取课程列表
         ************************************************************/
        selectcourse(){
            this.tableload = true
            this.courselist = []
            if(this.formItem.start_time!='' && this.formItem.end_time!=''&&this.infoOld.teacher_leave_id!=null && this.infoOld.user_id!=null)
            this.$http.get(`api/leave/v1/teacher_leave/course?start_time=${this.formItem.start_time}&end_time=${this.formItem.end_time}&teacher_leave_id=${this.infoOld.teacher_leave_id}&user_id=${this.infoOld.user_id}`).then((response) => {
                if (response.data.length != 0){
                        response.data.forEach(el=>{
                            this.courselist.push({
                                course:`${el.date} ${el.week_id.dictionary_name.zh} ${el.class_type.name.zh} ${el.course_id.course_name.zh}`,
                                course_id:el.course_id.id,
                                teacher:[],
                                seleced_id:'',
                                course_arrange_id:el.course_arrange_id,
                                cycle:el.cycle,
                            })
                            let arr = [];
                            arr.push({
                                id:item.course_id.id,
                                name:item.course_id.course_name.zh,
                            })
                            this.curriculumList = arr.filter(item=> item.id==item.id)
                        })
                        this.formState(this.curriculumList[0].id)
                        this.tableload = false;
                    }else{
                        this.tableload = false;				  
                    }
            }).catch(err => {
                if (err.code && err.code == 422) {
                    this.$Message.error(err.message);
                }
            })
        },
        /************************************************************
         * 选择课程获取教师
         ************************************************************/
        formState(val){
            if(val!=null){
                this.curriculumId = val
                this.course(val)
            }
        },
        /************************************************************
         * 获取教师
         ************************************************************/
        course(id){    
            this.$http.get(`api/leave/v1/teacher_leave/teacher/${id}`).then((response) => {
                let ss = []
                response.data.forEach(item=>{
                    ss.push({
                        value:item.user_id,
                        label:item.teacher_name.zh?item.teacher_name.zh:item.teacher_name.mn
                    })
                })
                this.courselist.forEach(el=>{
                    el.teacher=ss
                })
            }).catch(err => {
                if (err.code && err.code == 422) {
                this.$Message.error(err.message);
            }
            })
        },
        /************************************************************
         * 获取请假分类
         ************************************************************/
        load() {  
            this.$http.get('api/dictionary/v1/dictionary/pidquerys?teacher_leave_kind').then(val=>{ 
                this.DictionaryList=val.data.teacher_leave_kind               
            }).catch(err => {
                if (err.code && err.code == 422) {
                    this.$Message.error(err.message);
                }
            })
        },
        /************************************************************
         * 选择是否调课
         ************************************************************/   
        whether(val){
            if(val == 1){
                this.selectcourse()
            }
        },
        /************************************************************
         * 提交
         ************************************************************/  
        submit(name){
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.btnload = true
                    if(this.formItem.start_time!='' && this.formItem.end_time!=''){
                            if (this.formItem.whether_class == 1) {
                                if (this.formItem.class.length != 0) {
                                    this.editSubmit()
                                } else {
                                    this.$Message.error("请选择调课信息");
                                    this.btnload = false
                                }
                            } else {
                                this.editSubmit()
                            }
                    }else {
                        this.$Message.error("请选择请假时间");
                        this.btnload = false
                    }
                } else {
                    this.$Message.error("验证失败");
                    this.btnload = false
                }
            })
        },
        /************************************************************
         * 执行修改数据
         ************************************************************/
        editSubmit () {
            this.$http.put(`${this.updateUrl}${this.infoId}`,this.formItem).then(val=>{
                
                this.$emit('requery',true) 
                this.$Message.success(val.message);
            }).catch(err => {
                if (err.code && err.code == 422) {
                    this.$Message.error(err.message);
                }
                this.btnload = false
            })
        },
        /************************************************************
         * 单条数据请求
         ************************************************************/ 
        infodata(){
            this.$http.get(`${this.editUrl}${this.infoId}`).then(val=>{ 
                console.log(val)
                this.infoOld = JSON.parse(JSON.stringify(val.data))  
                this.time_status = 'edit'
                this.formItem.teacher_leave_id = parseInt(this.infoOld.user_id)                               
                this.formItem.teacher_leave_kind = parseInt(this.infoOld.teacher_leave_kind)
                this.formItem.whether_class = parseInt(this.infoOld.whether_class)
                this.formItem.start_time = this.infoOld.start_time
                this.formItem.end_time = this.infoOld.end_time
                this.formItem.teacher_leave_reason= this.infoOld.teacher_leave_reason
                this.leavedate =[this.infoOld.start_time,this.infoOld.end_time]
                if(this.infoOld.leave_days!=''){
                    this.formItem.leave_days = this.infoOld.leave_days
                }else{
                    this.formItem.leave_days = '0'
                }
                this.formItem.examine_id = parseInt(this.infoOld.examine.examine_id)   
                if(this.infoOld.whether_class==1){
                    this.editcourse(this.infoOld.start_time,this.infoOld.end_time,this.infoOld.teacher_leave_id,this.infoOld.user_id)
                }
            }).catch(err => {
                console.log(err);
            })
        },
        /************************************************************
         * 修改时的课程
         ************************************************************/
        editcourse(star,end,teacherId,userId){
            this.courselist = []
            this.$http.get(`api/leave/v1/teacher_leave/course?start_time=${star}&end_time=${end}&teacher_leave_id=${teacherId}&user_id=${userId}`).then((response) => {
                let arr = [];
                response.data.forEach(el=>{
                    this.courselist.push({
                        course:`${el.date} ${el.week_id.dictionary_name.zh} ${el.class_type.name.zh} ${el.course_id.course_name.zh}`,
                        course_id:el.course_id.id,
                        teacher:[],
                        seleced_id:el.teacher.user_id,
                        course_arrange_id:el.course_arrange_id,
                        cycle:el.cycle,
                    })
                    if(el.teacher.user_id!=null){
                        arr.push({
                            user_id:el.teacher.user_id,
                            course_arrange_id:el.course_arrange_id,
                            cycle:el.cycle,
                        })
                    }
                })
                this.formItem.class = arr
                this.curriculumList.push({
                    id:response.data[0].course_id.id,
                    name:response.data[0].course_id.course_name.zh,
                })
                this.curriculumId = response.data[0].course_id.id
                this.formState(this.curriculumId)
            });
        },
      
    },
    mounted(){
        this.infodata();
        this.load();
    },
    watch:{
        'formItem.end_time'(val,data){
            if(val != data && this.time_status != 'edit'){
                this.selectcourse()
            }
        }
	},
}
</script>
